package com.company.ems.controller;

import com.company.ems.dto.EmployeeQueryDTO;
import com.company.ems.dto.PageDTO;
import com.company.ems.mapper.EmployeeMapper;
import com.company.ems.model.Employee;
import com.company.ems.model.User;
import com.company.ems.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class EmployeeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pathInfo = request.getPathInfo();

        // 修改为正确处理pathInfo为null的情况
        if (pathInfo == null) {
            // 当请求是 /employee 时，pathInfo为null，直接调用list方法
            list(request, response);
        } else if (pathInfo.equals("/")) {
            list(request, response);
        } else if (pathInfo.equals("/add")) {
            request.getRequestDispatcher("/add.jsp").forward(request, response);
        } else if (pathInfo.equals("/edit")) {
            edit(request, response);
        } else if (pathInfo.equals("/view")) {
            view(request, response);
        } else if (pathInfo.equals("/delete")) {
            delete(request, response);
        } else {
            response.sendRedirect(request.getContextPath() + "/error/404.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 添加这行代码设置请求的字符编码为UTF-8
        request.setCharacterEncoding("UTF-8");
        
        String pathInfo = request.getPathInfo();
    
        if (pathInfo.equals("/save")) {
            save(request, response);
        } else if (pathInfo.equals("/update")) {
            update(request, response);
        } else {
            doGet(request, response);
        }
    }

    // 列表查询
    private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        EmployeeQueryDTO queryDTO = new EmployeeQueryDTO();
        queryDTO.setName(request.getParameter("name"));
        queryDTO.setDepartment(request.getParameter("department"));
        queryDTO.setPosition(request.getParameter("position"));

        // 处理分页参数
        String pageNumStr = request.getParameter("pageNum");
        if (pageNumStr != null && !pageNumStr.isEmpty()) {
            queryDTO.setPageNum(Integer.parseInt(pageNumStr));
        }

        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);

        List<Employee> employees = employeeMapper.findByCondition(queryDTO);
        int total = employeeMapper.countByCondition(queryDTO);

        PageDTO<Employee> pageDTO = new PageDTO<>();
        pageDTO.setList(employees);
        pageDTO.setTotal(total);
        pageDTO.setPageNum(queryDTO.getPageNum());
        pageDTO.setPageSize(queryDTO.getPageSize());
        pageDTO.setPages((total + queryDTO.getPageSize() - 1) / queryDTO.getPageSize());

        request.setAttribute("pageDTO", pageDTO);
        request.setAttribute("queryDTO", queryDTO);
        request.getRequestDispatcher("/list.jsp").forward(request, response);

        sqlSession.close();
    }

    // 查看详情
    private void view(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String idStr = request.getParameter("id");
        if (idStr == null || idStr.isEmpty()) {
            response.sendRedirect(request.getContextPath() + "/employee");
            return;
        }

        int id = Integer.parseInt(idStr);
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
        Employee employee = employeeMapper.findById(id);

        if (employee != null) {
            request.setAttribute("employee", employee);
            request.getRequestDispatcher("/view.jsp").forward(request, response);
        } else {
            response.sendRedirect(request.getContextPath() + "/employee");
        }

        sqlSession.close();
    }

    // 编辑
    private void edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String idStr = request.getParameter("id");
        if (idStr == null || idStr.isEmpty()) {
            response.sendRedirect(request.getContextPath() + "/employee");
            return;
        }

        int id = Integer.parseInt(idStr);
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
        Employee employee = employeeMapper.findById(id);

        if (employee != null) {
            request.setAttribute("employee", employee);
            request.getRequestDispatcher("/edit.jsp").forward(request, response);
        } else {
            response.sendRedirect(request.getContextPath() + "/employee");
        }

        sqlSession.close();
    }

    // 保存新增
    private void save(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");

        Employee employee = new Employee();
        employee.setName(request.getParameter("name"));
        employee.setDepartment(request.getParameter("department"));
        employee.setPosition(request.getParameter("position"));
        employee.setSalary(new BigDecimal(request.getParameter("salary")));
        employee.setEmail(request.getParameter("email"));
        employee.setPhone(request.getParameter("phone"));

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            employee.setHireDate(sdf.parse(request.getParameter("hireDate")));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        employee.setCreatedBy(user.getId());

        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
        employeeMapper.insert(employee);
        sqlSession.commit();
        sqlSession.close();

        response.sendRedirect(request.getContextPath() + "/employee");
    }

    // 更新
    private void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String idStr = request.getParameter("id");
        if (idStr == null || idStr.isEmpty()) {
            response.sendRedirect(request.getContextPath() + "/employee");
            return;
        }

        int id = Integer.parseInt(idStr);

        Employee employee = new Employee();
        employee.setId(id);
        employee.setName(request.getParameter("name"));
        employee.setDepartment(request.getParameter("department"));
        employee.setPosition(request.getParameter("position"));
        employee.setSalary(new BigDecimal(request.getParameter("salary")));
        employee.setEmail(request.getParameter("email"));
        employee.setPhone(request.getParameter("phone"));

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            employee.setHireDate(sdf.parse(request.getParameter("hireDate")));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
        employeeMapper.update(employee);
        sqlSession.commit();
        sqlSession.close();

        response.sendRedirect(request.getContextPath() + "/employee");
    }

    // 删除
    private void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String idStr = request.getParameter("id");
        if (idStr == null || idStr.isEmpty()) {
            response.sendRedirect(request.getContextPath() + "/employee");
            return;
        }

        int id = Integer.parseInt(idStr);
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
        employeeMapper.delete(id);
        sqlSession.commit();
        sqlSession.close();

        response.sendRedirect(request.getContextPath() + "/employee");
    }
}